//
//  FilterManager.m
//  Task Views
//
//  Created by Chris Karr on 3/15/09.
//  Copyright 2009 Chris J. Karr. All rights reserved.
//

#import "FilterManager.h"
#import "FilterRowTemplate.h"

@implementation FilterManager


- (IBAction) filter:(id) sender
{
	[filterWindow makeKeyAndOrderFront:sender];
}

- (IBAction) add:(id) sender
{
	NSMutableDictionary * filter = [NSMutableDictionary dictionary];
	[filter setValue:@"New Filter" forKey:@"name"];
	NSPredicate * predicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObject:
																				  [NSPredicate predicateWithFormat:@"(%K != %@)", @"name", @"New Task", nil]]];
	
	[filter setValue:[NSKeyedArchiver archivedDataWithRootObject:predicate] forKey:@"filter"];
	
	[filters addObject:filter];
}

- (NSArray *) fieldNames
{
	NSArray * fieldsList = [fields arrangedObjects];
	
	NSMutableArray * names = [NSMutableArray array];
	for (id name in fieldsList)
		[names addObject:[name valueForKey:@"name"]];
	
	return names;
}

- (IBAction) copy:(id) sender
{
	NSMutableDictionary * filter = [[filters selectedObjects] lastObject];

	NSMutableDictionary * newFilter = [NSMutableDictionary dictionaryWithDictionary:filter];
	
	[filters addObject:newFilter];
}

- (IBAction) menu:(id) sender
{
	NSRect frame = [sender frame];
    NSPoint menuOrigin = [[sender superview] convertPoint:NSMakePoint(frame.origin.x, frame.origin.y+frame.size.height+40) toView:nil];
	
    NSEvent * event =  [NSEvent mouseEventWithType:NSLeftMouseDown
                                         location:menuOrigin
                                    modifierFlags:NSLeftMouseDownMask // 0x100
                                        timestamp:0
                                     windowNumber:[[sender window] windowNumber]
                                          context:[[sender window] graphicsContext]
                                      eventNumber:0
                                       clickCount:1
                                         pressure:1];
	
	[NSMenu popUpContextMenu:[sender menu] withEvent:event forView:sender];
}

- (void) observeValueForKeyPath:(NSString *) keyPath ofObject:(id) object change:(NSDictionary *) change context:(void *) context
{
	NSMutableArray * ruleTemplates = [NSMutableArray arrayWithArray:[editor rowTemplates]];
	
	NSPredicateEditorRowTemplate * original = [ruleTemplates lastObject];
	
	NSMutableSet * lefts = [NSMutableSet setWithObjects:[NSExpression expressionForKeyPath:@"name"], 
													    [NSExpression expressionForKeyPath:@"source"], nil];
	
	for (NSString * item in [self fieldNames])
	{
		NSExpression * keyPath = [NSExpression expressionForKeyPath:item];
		[lefts addObject:keyPath];
	}

	NSSortDescriptor * sort = [[NSSortDescriptor alloc] initWithKey:@"keyPath" ascending:YES selector:@selector(caseInsensitiveCompare:)];
	
	FilterRowTemplate * template = [[FilterRowTemplate alloc] initWithLeftExpressions:[[lefts allObjects] sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]]
														 rightExpressionAttributeType:NSStringAttributeType
																			 modifier:[original modifier]
																			operators:[original operators]
																			  options:[original options]];

	[sort release];
	
	[ruleTemplates removeLastObject];
	[ruleTemplates addObject:template];
	
	[editor setRowTemplates:ruleTemplates];
	
	[template release];
}	

- (void) awakeFromNib
{
	[self observeValueForKeyPath:@"arrangedObjects" ofObject:fields change:nil context:NULL];
	
	NSDictionary * keyDict = [NSDictionary dictionaryWithObject:@"name" forKey:@"name"];
	
	if (![[fields arrangedObjects] containsObject:keyDict])
		[fields addObject:keyDict];
	
	NSSortDescriptor * sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
	[fields setSortDescriptors:[NSArray arrayWithObject:sort]];
	[sort release];
	
	[fields addObserver:self forKeyPath:@"arrangedObjects" options:0 context:NULL];
	
	[filterWindow setFloatingPanel:NO];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectFilter:) name:FILTER_NOTE object:nil];
}

- (void) selectFilter:(NSNotification *) theNote
{
	[filters setSelectedObjects:[NSArray arrayWithObject:[theNote object]]];
}

@end
